package com.project.common.filter;

import com.alibaba.fastjson.JSON;
import com.framework.core.result.APIObjResponse;
import com.project.base.BaseController;
import com.project.common.headers.Headers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
* @Description:   系统统一拦截认证
* @Author:         wangzhiqiang
* @CreateDate:     2019-02-21 17:02
* @Version:        1.0
*/
@Slf4j
public class AllRequestFilter implements Filter {

    /**
     * 无需APPKEY拦截的URL
     */
    private String[] EXCLUDED_ARRAY = {"/wx/payNotify","/imgCode","/user/setTusers","/user/getTusers","/user/delTusers","/wx/recoveryPayNotify",
    "/export/exportProductData","/export/exportUserData"};

    /**
     * 系统Key标识
     */
    //TODO 新项目时需替换为自己项目标识
    static final String OKBUYD_KEY = "elephant_family_pro";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();

        String okbuyd_key = request.getHeader(Headers.OKBNYD_KEY);

        if (!request.getMethod().equals("OPTIONS")){
            String ip = BaseController.getRealIP(request);
            log.info("IP[{}],请求接口[{}]", ip, uri);
        }

        if (request.getMethod().equals("OPTIONS") || !this.needAppkey(uri) || (StringUtils.isNotEmpty(okbuyd_key) && OKBUYD_KEY.equals(okbuyd_key))){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.setStatus(200);
            APIObjResponse objResp = APIObjResponse.refunse();
            String jsonObject = JSON.toJSONString(objResp);
            response.getWriter().write(jsonObject);
            response.getWriter().flush();
            response.getWriter().close();
            log.info("系统拒绝提供服务!,URI: {}", uri);
        }
    }

    /**
     * 无需拦截APPKEY的URL
     * @param uri
     * @return true需拦截,false无需拦截
     */
    public boolean needAppkey(String uri){
        //解决部署到tomcat后接口名有前缀,导致无需的登录URL也需要登录问题
        if (uri.startsWith("/elephant-family")){
            uri = uri.substring("/elephant-family".length());
        }

        //放开swagger相关文件
        if(uri.contains("swagger") || uri.contains("api-docs") || uri.contains("csrf")){
            return false;
        }

        String[] excludedUrl = this.EXCLUDED_ARRAY; //获取无需拦截的URL
        if (null != excludedUrl && excludedUrl.length > 0){
            for (String u : excludedUrl){
                if (uri.equals(u)){
                    return false;//如果当前URL在无需拦截的数组中，则无需拦截
                }
            }
        }

        return true;
    }

    @Override
    public void destroy() {

    }

}
